package com.engineering.elink.service.impl;

import java.text.ParseException;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.engineering.elink.common.CoinRuleEnum;
import com.engineering.elink.dao.PersonMapper;
import com.engineering.elink.dao.SignMapper;
import com.engineering.elink.dao.UserMapper;
import com.engineering.elink.domain.Person;
import com.engineering.elink.domain.Sign;
import com.engineering.elink.service.CoinBalanceService;
import com.engineering.elink.service.SignService;
import com.engineering.elink.util.DateUtil;

@Service
public class SignServiceImpl implements SignService {
	@Autowired
	private PersonMapper personMapper;
	@Autowired
	private SignMapper signMapper;
	@Autowired
	private UserMapper  userMapper;
	@Autowired
	private CoinBalanceService coinBalanceService;
	
	@Override
	@Transactional
	public synchronized boolean signUp(String userId) {
		Sign sign = signMapper.selectByUserIdAndDateTime(userId, new Date());
		// 判断当天是否签到
		if (sign == null) {
			Sign lastSign = signMapper.selectLastSignByUserId(userId);
			Person person = personMapper.selectByUserId(userId);
			// 如果没有签到记录 直接更新最大次数
			if (lastSign != null) {//最后一次签到
				Date lastSignDateTime = lastSign.getCreateTime();
				Date currentSignDateTime = new Date();
				int days = 0;
				try {
					days = DateUtil.daysBetween(lastSignDateTime, currentSignDateTime);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				// 如果是继续签到，则更新连续签到次数
				if (days == 1) {
					person.setSuccesiveSignCount(person.getSuccesiveSignCount() + 1);
					// 如果超过最大次数，更新最大连续签到次数
					if (person.getSuccesiveSignCount() > person.getMaxSignCount()) {
						person.setMaxSignCount(person.getSuccesiveSignCount());
					}
					personMapper.updateByUserIdSelective(person);
				} else {//不是连续签到
					person.setSuccesiveSignCount(0);//重置连续签到的次数
					personMapper.updateByUserIdSelective(person);
				}
			}else {//没有签到记录
				person.setSuccesiveSignCount(1);
				person.setMaxSignCount(1);
				personMapper.updateByUserIdSelective(person);
			}
			// 更新签到
			sign = new Sign();
			sign.setCreateTime(new Date());
			sign.setUserId(userId);
			signMapper.insertSelective(sign);
			
			//更新积分
			coinBalanceService.modifyCoin(userId, CoinRuleEnum.SIGN.getIndex(), 0, userId, "");
			return true;
		}
		return false;
	}

	/**
	 * 返回true 已签到 返回false 未签到
	 */
	@Override
	public boolean checkSign(String userId) {
		// 判断当天是否签到
		Sign sign = signMapper.selectByUserIdAndDateTime(userId, new Date());
		if (sign == null) {
			return false;
		}
		return true;
	}

}
